/*
 * @Author: ljk
 * @Date: 2023-06-02 11:18:39
 * @LastEditors: ljk
 * @LastEditTime: 2023-07-26 10:08:08
 * @Description: 生产者与消费者进程
 */
#include "blockQueue.hpp"

void* producerProcess(void* args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);
    string opers = "+-*/%";
    while (true)
    {
        sleep(1);
        // 1.通过某种渠道获取数据(生产数据)
        int x = rand() % 20 + 1;
        int y = rand() % 10 + 1;
        char op = opers[rand() % opers.size()];
        // 2.数据推送到blockqueue
        char* name = new char[32];
        snprintf(name, 32, "thread-%d", rand() % 5);
        Task task(x, y, op, name);
        bq->push(task);
        cout << "producer Task: " << task.formatArg() << "?" << endl;
    }
}
void* consumerProcess(void* args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task>*>(args);
    while (true)
    {
        Task task;
        // 1.从blockqueue中获取数据
        bq->pop(&task);
        task();
        // 2.结合某种业务处理数据
        cout << "consumer Task: " << task.formatArg() << task.formatRes() << endl;
    }
}
int main()
{
    srand((uint64_t)time(nullptr) ^ getpid());
    //BlockQueue<int> *bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    //单生产单消费  ->  多生产多消费
    //因为用的是同一把锁，所以注定了生产者与生产者, 消费者与消费者, 生产者与消费者之间注定是互斥的
    pthread_t producer[2], consumer[3];
    pthread_create(&producer[0], nullptr, producerProcess, bq);
    pthread_create(&producer[1], nullptr, producerProcess, bq);

    pthread_create(&consumer[0], nullptr, consumerProcess, bq);
    pthread_create(&consumer[1], nullptr, consumerProcess, bq);
    pthread_create(&consumer[2], nullptr, consumerProcess, bq);


    pthread_join(producer[0], nullptr);
    pthread_join(producer[1], nullptr);
    pthread_join(consumer[0], nullptr);
    pthread_join(consumer[1], nullptr);
    pthread_join(consumer[2], nullptr);

    delete bq;
    return 0;
}